<template>
  <div style="display: inline-block;">
    <el-button
      class="send-sms-button"
      type="primary"
      style="margin-left: 3px;"
      @click="sendSms"
      :disabled="seconds>0"
      v-text="seconds>0?seconds+' 秒重发':'发送验证码'">
    </el-button>
  </div>
</template>

<script>
const waitSeconds=60
export default {
  name: "SendSms",
  props:{
    getMobile:Function,
    eventType:String
  },
  mounted() {
    let $this=this
    // $this.seconds=120
    setInterval(function () {
      if ($this.seconds>0){
        $this.seconds--
        localStorage.setItem($this.localStorageKey,$this.seconds)
        $this.$forceUpdate()
      }
    },1000)
    var cacheSeconds=localStorage.getItem(this.localStorageKey);
    if (cacheSeconds && cacheSeconds>0){
      $this.seconds=cacheSeconds
    }else{
      $this.seconds=0
    }

  },
  data:function () {
    return {
      localStorageKey:this.$props.eventType+'__sms',
      seconds:0,
    }
  },
  methods: {
    sendSms:function () {
      if (this.seconds>0){
        return
      }
      let username=this.$props.getMobile()+''
      var regExp = /^1[3456789]\d{9}$/;
      if (regExp.test(username)){
        this.bus.$emit('SendSmsDialogCallBus',username,this.$props.eventType,this.setCache);
      }else{
        return this.$message.error('手机号码错误'+username)
      }
    },
    setCache:function () {
      this.seconds=waitSeconds
      localStorage.setItem(this.localStorageKey,this.seconds)
    }
  }
}
</script>

<style scoped>
.send-sms-button{ padding: 10px 5px;}
</style>
